﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using COMOSOFT.Class;
using COMOSOFT.Main;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using System.IO;

namespace COMOSOFT.MatarialManagement.Forms
{
    public partial class FrmMALibrary : Form
    {        
        ClassShare cls = new ClassShare("FrmMALabriry");        
        int MAID,MADID;
        DataTable dbTemp = null;
        Image img;
        int numrow;
        string path1 = null;
        string path2 = null;
        public FrmMALibrary(int _MAID)
        {
            InitializeComponent();
            this.MAID = _MAID;          
            if (MAID == -1)
            {
                mASourceTableAdapter.Fill(dataSetMatarial.MASource, MAID);                
            }
        }
      
        #region [LoadData]
        public void LoadData()
        {
            try
            {
                employeeTableAdapter.Fill(dataSetOrderManagement.Employee);
                customsCodeTableAdapter.Fill(dataSetMatarial.CustomsCode);
                supplierTableAdapter.Fill(dataSetMatarial.Supplier);
                if (MAID > 0)
                {
                    mASourceTableAdapter.Fill(dataSetMatarial.MASource, MAID);
                    mASourceDetailsTableAdapter.Fill(dataSetMatarial.MASourceDetails, MAID);
                    this.Text = "Item: " + txt_EnName.Text + "-" + txt_Art.Text;
                    groupControl_Details.Enabled = true;

                    //Load Image

                   
                    dbTemp = new DataTable();
                    dbTemp.Columns.Add("ID");
                    dbTemp.Columns.Add("Img1", typeof(object));
                    dbTemp.Columns.Add("Img2", typeof(object));
                    DataTable dbMA = dataSetMatarial.MASourceDetails;
                    numrow = dbMA.Rows.Count;
                    if (dbMA.Rows.Count > 0)
                    {
                        for (int i = 0; i < dbMA.Rows.Count; i++)
                        {
                            DataRow newrow = dbTemp.NewRow();
                            string path1 = dbMA.Rows[i]["Picture1"].ToString();
                            string path2 = dbMA.Rows[i]["Picture2"].ToString();

                            if (path1 != null && path1 != "")
                            {
                                byte[] img = System.IO.File.ReadAllBytes(path1);
                                newrow["Img1"] = img;
                            }
                            else
                            {
                                byte[] NoImg = System.IO.File.ReadAllBytes(@"D:\\noImage.gif");
                                newrow["Img1"] = NoImg;
                            }

                            if (path2 != null && path2 != "")
                            {
                                byte[] img = System.IO.File.ReadAllBytes(path2);
                                newrow["Img2"] = img;
                            }
                            else
                            {
                                byte[] NoImg = System.IO.File.ReadAllBytes(@"D:\\noImage.gif");
                                newrow["Img2"] = NoImg;
                            }
                            newrow["ID"] = dbMA.Rows[i]["MADID"];
                            dbTemp.Rows.Add(newrow);
                        }
                    }
                    //-------------------------- 
                }
            }
            catch
            {
                MessageBox.Show("Disconnect database! Please try again!", "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region [Show Image]
        private Image LoadImg(string ID, int row,string flag)
        {
            if (dbTemp.Rows.Count > row && dbTemp.Rows[row]["ID"].ToString() == ID)
            {                
                using (System.IO.MemoryStream str = new System.IO.MemoryStream(dbTemp.Rows[row]["Img"+flag] as byte[]))
                {
                    img = Image.FromStream(str);
                    return img;
                }
            }          
            return img;
        }          
        // Show Image
        private void gridView_MALibraryDetails_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;                
                if (!view.IsNewItemRow(e.ListSourceRowIndex) && numrow>e.ListSourceRowIndex)
                {
                    if (e.Column.FieldName == "Pictureone" && e.IsGetData)
                        e.Value = LoadImg(view.GetRowCellValue(e.ListSourceRowIndex, "MADID").ToString(), e.ListSourceRowIndex, "1");
                    if (e.Column.FieldName == "Picturetwo" && e.IsGetData)
                        e.Value = LoadImg(view.GetRowCellValue(e.ListSourceRowIndex, "MADID").ToString(), e.ListSourceRowIndex, "2");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #endregion

        #region [Upadte Master]
        public void AddNew()
        {
            mASourceBindingSource.AddNew();
            txt_CreateDate.EditValue = DateTime.Now.ToShortDateString();
            txt_Creater.EditValue = Convert.ToInt64(ClassShare.Usid);
        }
        public void UpdateMAL()
        {
            try
            {
                if (MAID == -1)
                {
                    //Insert                   
                    mASourceBindingSource.EndEdit();
                    mASourceTableAdapter.Update(dataSetMatarial.MASource);
                    dataSetMatarial.MASource.AcceptChanges();
                    if (groupControl_Details.Enabled == false)
                    {
                        groupControl_Details.Enabled = true;
                        MAID = Convert.ToInt32(txt_MAID.Text);
                        this.Text ="Item: "+ txt_EnName.Text + "-" + txt_Art.Text;
                        
                    }
                }
                else
                {
                    //update
                    mASourceBindingSource.EndEdit();
                    mASourceTableAdapter.Update(dataSetMatarial.MASource);
                    dataSetMatarial.MASource.AcceptChanges();
                }
                MessageBox.Show("Update Successfully!", "Finishing....", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                
            }
        }
        public void DeleteMALib()
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to delete?", "Delete item", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    dataSetMatarial.MASource.Rows[0].Delete();
                    mASourceTableAdapter.Update(dataSetMatarial.MASource);
                    dataSetMatarial.MASource.AcceptChanges();
                    this.Close();                    
                }
            }
            catch
            {
                MessageBox.Show("Can't delete object! Have a object using it!", "Warning....", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #endregion

        #region [Update Details]
        private void gridView_MALibraryDetails_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                GridView view =sender as GridView;               
                if (MAID != -1)
                {
                    if (path1 == null)
                        path1 = view.GetFocusedDataRow()["Picture1"].ToString();
                    if(path2==null)
                        path2 = view.GetFocusedDataRow()["Picture2"].ToString();
                }
                view.SetFocusedRowCellValue("MAID", txt_MAID.Text);

                mASourceDetailsBindingSource.EndEdit();
                mASourceDetailsTableAdapter.Update(dataSetMatarial.MASourceDetails);
                dataSetMatarial.MASourceDetails.AcceptChanges();

                DataTable dtb = cls.GetData("sp_MASDetailsInsert");                
                if(dtb.Rows.Count>0)
                {
                    MADID = Convert.ToInt32(dtb.Rows[0][0]);
                }                               
                cls.UpdateData("sp_MASDetailsUpdate", new string[3] { "@MADID", "@img1", "@img2" }, new object[3] { MADID, path1, path2 });
                MessageBox.Show("Update Successfully!", "Finish....", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();               
            }
            catch
            {
                MessageBox.Show("Not thing Update!", "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to delete?", "Delete item", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    int MADID = Convert.ToInt32(gridView_MALibraryDetails.GetFocusedDataRow()["MADID"]);
                    cls.UpdateData("sp_MADetailsDelete", new string[1] { "@MADID" }, new object[1] { MADID });
                    mASourceDetailsTableAdapter.Fill(dataSetMatarial.MASourceDetails, MAID);
                }
            }
            catch
            {
                MessageBox.Show("Can't delete this object! Because it using in MAListDetails!!", "Delete Fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }    
        #endregion

        private void gridView_MALibraryDetails_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {           
            gridView_MALibraryDetails.SetFocusedRowCellValue("CreateBy", ClassShare.Usid);
            gridView_MALibraryDetails.SetFocusedRowCellValue("PriceDate", DateTime.Now.ToShortDateString());
        }
        // Update Supplier
        #region [Add Supplier]
        private void repositoryItemGridLookUpEdit_supplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString()=="1")
            {
                supplierContactTableAdapter.Fill(dataSetMatarial.SupplierContact,-1);
                supplierBindingSource.AddNew();
                gridView_NewSupplier.SetFocusedRowCellValue("MASUPID", txt_ID.Text);
                dockPanel_Supplier.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - dockPanel_Supplier.Width, Screen.PrimaryScreen.WorkingArea.Height / 2 - dockPanel_Supplier.Height);
                groupControl_SupDetails.Enabled = false;
                dockPanel_Supplier.Show();
            }
        }

        private void bnt_ok_Click(object sender, EventArgs e)
        {
            try
            {
                supplierBindingSource.EndEdit();
                supplierTableAdapter.Update(dataSetMatarial.Supplier);
                dataSetMatarial.Supplier.AcceptChanges();
                if (groupControl_SupDetails.Enabled == false)
                    groupControl_SupDetails.Enabled = true;
                dockPanel_Supplier.Text = "Supplier: " + txt_Fullname.Text;
            }
            catch
            {
                MessageBox.Show("Not thing update!", "Update Fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        private void FrmMALibrary_Load(object sender, EventArgs e)
        {         
            dockPanel_Supplier.Hide();
        }

        #region [Upadate Supplier Details]
        private void gridView_NewSupplier_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                supplierContactBindingSource.EndEdit();
                supplierContactTableAdapter.Update(dataSetMatarial.SupplierContact);
                dataSetMatarial.SupplierContact.AcceptChanges();
                supplierTableAdapter.Fill(dataSetMatarial.Supplier);               
            }
            catch
            {
                MessageBox.Show("Not thing update!", "Update Fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Add CusCode]
        private void gridLookUpEdit_CusCode_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {               
                customsCodeBindingSource.EndEdit();
                customsCodeTableAdapter.Update(dataSetMatarial.CustomsCode);
                dataSetMatarial.CustomsCode.AcceptChanges();
            }
            catch
            {
                MessageBox.Show("Not thing update!", "Update Fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txt_CusCode_Click(object sender, EventArgs e)
        {
            //GridLookUpEdit glk = sender as GridLookUpEdit;
            //GridView view = glk.Properties.View as GridView;
            //view.SetFocusedRowCellValue("CreateBy", ClassShare.Usid);
            //view.SetFocusedRowCellValue("CreateDate", DateTime.Now.ToString("dd-MM-yyyy"));
        }
        #endregion

        private void bnt_finish_Click(object sender, EventArgs e)
        {
            dockPanel_Supplier.Close();
        }

        #region [Choose Image]
        private void repositoryItemImageEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString() != "0")
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.InitialDirectory = @"C:\";
                dlg.Filter = "All file (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
                dlg.Title = "Please select an image file to encrypt.";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (e.Button.Tag.ToString() == "1")
                        path1 = dlg.FileName;
                    else
                        path2 = dlg.FileName;
                }           
            }
        }
        #endregion    
    }
}
